//
//  BaseHttpRequestModel.m
//  GSDache
//
//  Created by tanyin on 16/11/28.
//  Copyright © 2016年 tanyin. All rights reserved.
//

#import "BaseHttpRequestModel.h"
#import "BaseHttpRequest.h"
#import <AFNetworking.h>

@interface BaseHttpRequestModel ()

@end

@implementation BaseHttpRequestModel
{
    BaseHttpRequest *_m_request;
}
- (instancetype)init {
    self = [super init];
    if (self) {
        _m_request = [[BaseHttpRequest alloc] init];
    }
    return self;
}

- (AFHTTPSessionManager *)requestSession {
    return _m_request.session;
}
#pragma mark - Setter

- (void)didRequestSuccessed:(requestServerSuccessed)successedhandler {
    _requestSuccessed = [successedhandler copy];
}

- (void)didRequestFailed:(requestServerFailed)failedHandler {
    _requestFailed = [failedHandler copy];
}

- (void)didRequestProgress:(requestServerProgress)progressHandler {
    _requestProgress = [progressHandler copy];
}
- (void)didRequestCompleted:(requestServerComplete)completeHander {
    _requestComplete = [completeHander copy];
}
#pragma mark - Init
- (HttpRequestMethod)requestMethod {
    return GET;
}
- (Class)responseClass {
    return [NSObject class];
}
-(NSString *)relativelyUrl{
    return nil;
}

-(NSString *)absoluteUrl{
    
    return [@"" stringByAppendingPathComponent:[self relativelyUrl]];
}

-(NSMutableArray *)uploadDatas{
    
    /*
     
     @[@{@"data": nil,
     @"fileName" :@"",
     @"name":@"",
     @"mimeType":@""
     }
     ];
     */
    return nil;
}

- (BOOL)shouldEncryption {
    return false;
}

-(NSDictionary *)headerParameter {
    
    return nil;
}

-(id)requestParameter {
    
    NSData *jsonData = [[self yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if (self.shouldEncryption) {
        //加密
    }
    return dic;
}

+ (NSArray *)modelPropertyBlacklist {
    return @[@"requestView",
             @"shouldShowLoadingAnimation",
             @"requestSuccess",
             @"requestServerSuccessWithPage",
             @"requestErrorWith",
             @"requestProgress",
             @"m_request",
             @"hudProgress"];
}

-(BOOL)modelCustomTransformToDictionary:(NSMutableDictionary *)dic{
    
    [dic removeObjectForKey:@"requestView"];
    [dic removeObjectForKey:@"shouldShowLoadingAnimation"];
    [dic removeObjectForKey:@"requestSuccess"];
    [dic removeObjectForKey:@"requestServerSuccessWithPage"];
    [dic removeObjectForKey:@"requestErrorWith"];
    [dic removeObjectForKey:@"requestProgress"];
    [dic removeObjectForKey:@"m_request"];
    return true;
}

- (void)requestServer {
    NSLog(@"\n%@ will request \nurl:%@\n%@", NSStringFromClass([self class]), [self absoluteUrl], [self yy_modelToJSONObject]);
//    WEAK_SELF
    switch ([self requestMethod]) {
        case POST: {
            if (self.uploadDatas.count > 0) {
                [_m_request postFile:self progress:^(NSProgress *progress) {
                    
                } success:^(NSURLSessionDataTask *task, id obj) {
                    if (self.requestComplete) {
                        self.requestComplete();
                    }
                    [self success:task data:obj];
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if (self.requestComplete) {
                        self.requestComplete();
                    }
                    [self failure:task error:error];
                }];
                
            }else {
                [_m_request post:self success:^(NSURLSessionDataTask *task, id obj) {
                    if (self.requestComplete) {
                        self.requestComplete();
                    }
                    [self success:task data:obj];
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if (self.requestComplete) {
                        self.requestComplete();
                    }
                    [self failure:task error:error];
                }];
            }
            
        }
            break;
        case GET: {
            
            [_m_request get:self success:^(NSURLSessionDataTask *task, id obj) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self success:task data:obj];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self failure:task error:error];
            }];
        }
            break;
        case PUT:{
            [_m_request put:self success:^(NSURLSessionDataTask *task, id obj) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self success:task data:obj];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self failure:task error:error];
            }];
        }
            break;
        case DELETE: {
            [_m_request delete:self success:^(NSURLSessionDataTask *task, id obj) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self success:task data:obj];
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                if (self.requestComplete) {
                    self.requestComplete();
                }
                [self failure:task error:error];
            }];
        }
            break;
        default:
            break;
    }
}


#pragma mark - Parser Function
-(BOOL)success:(NSURLSessionDataTask *)task data:(id)obj {
    if (!obj) {
        if (self.requestFailed) {
            self.requestFailed([NSError errorWithDomain:@"Service Error" code:999 userInfo:nil]);
        }
        return false;
    }
    if (self.shouldEncryption) {
        //解密
    }
    return true;
}

-(void)failure:(NSURLSessionDataTask *)task error:(NSError *)error{
    
//    NSError *parserError = [NSError errorWithDomain:error.domain code:error.code userInfo:nil];
//    id obj = nil;
//    if (error.code != NO_NETWORK &&
//        error.userInfo.allKeys.count) {
//        
//        NSInteger errorCode = [error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey] statusCode];
//        id objData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
//        if (objData) {
//            
//            obj = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableLeaves error:nil];
//            if (obj && obj[@"msg"] && obj[@"code"]) {
//                parserError = [NSError errorWithDomain:obj[@"msg"] code:[obj[@"code"] integerValue] userInfo:nil];
//                
//            }else {
//                
//                parserError = [NSError errorWithDomain:error.localizedDescription code:errorCode userInfo:nil];
//            }
//        }else{
//            
//            parserError = [NSError errorWithDomain:error.localizedDescription code:error.code userInfo:error.userInfo];
//        }
//    }
//    
//    if (self.requestFailed) {
//        self.requestFailed(parserError);
//    }
}

- (void)dealloc {
    
    NSLog(@"dealloc");
}
@end
